import { useState, useRef } from "react"
import style from './index.module.scss'
import { Button, Input, Table, Tag, message, Modal } from "antd"
import { AddDelParamsFnc, RemoveParamsFnc } from '@/api/params'
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import useSyncState from "@/utils/tongbu"
import AddEdit from "../AddEdit"

const Tables = ({activeName, btnDisabled, dataSource, catID, cascaderValue, getTable}: any) => {
 const columns = [
   {title: '商品名称', dataIndex: 'attr_name', key: 'goods_name', width: 400, ellipsis: true},
   {title: '操作', width: 180, render: (record: {attr_id: number}) => {
    return (
      <>
       <Button type='primary' size='small' icon={<EditOutlined/>} onClick={() => editBox(record)}>编辑</Button> 
       <Button type="primary" danger size='small' icon={<DeleteOutlined/>} onClick={() => deleteParamsAttr(record)} style={{margin: '0 6px 0'}}>删除</Button> 
      </>
    )
   }}
 ]      

 const [pageNow, setPageNow] = useState(1)
 const [pageSize, setPageSize] = useState(2)
 const [total] = useState(0)
 const [iptVisible, setIptVisible] = useSyncState(false) // tag ipt显示还是隐藏
 const iptRef = useRef<any>(null)
 const [isModalOpen, setIsModalOpen] = useState(false) // 添加 修改盒子
 const [type, setType] = useState('') // 要么是add 要么是edit
 const [attrID, setAttrID] = useState('') // attrID 打开编辑盒子使用

  // 更改每页数量 或者 切换当前页 给子组件使用
  const sizeCurrentChange = (current: number, pageSize: number) => {
    setPageNow(current)
    setPageSize(pageSize)
  }

  // 添加删除 tag公共方法
  const publicAddDel = async (record: any, msg: string) => {
    const res = await AddDelParamsFnc(record.cat_id, record.attr_id, {
      attr_name: record.attr_name,
      attr_sel: record.attr_sel,
      attr_vals: record.attr_vals
    })
    if(res.data.meta.status === 200) {
      message.success(msg, 0.5)
    }
  }

  // 删除tag标签
  const tagClose = (record: any, index: number) => {
    let arr = record.attr_vals.trim().split(" ")
    arr.splice(index, 1).join(' ')
    let arrB = arr.join(' ')
    record.attr_vals = arrB
    publicAddDel(record, '删除成功')
  }

  // 添加tag标签 并隐藏input
  const hideIpt = async (e:any , record: any) => {
    setIptVisible(false)
    if(e.target.value !== '') {
      record.attr_vals = record.attr_vals.concat(' ' + e.target.value)
      publicAddDel(record, '添加成功')
    }
  }

  // 显示ipt
  const showIpt = () => {
    setIptVisible(true, () => {
      iptRef.current.focus()
    })
  }
  
  // 要么是ipt显示 要么是btn显示
  const showBtnTags = (record: any) => {
    if(iptVisible) {
      return <Input ref={iptRef} style={{width: '150px'}} onBlur={(e) => hideIpt(e, record)}/>
    } else{
      return <Button onClick={() => showIpt()}>+ new Tag</Button>
    }
  }

  // 显示 tag标签
  const subTags = (record: any) => {
    if(record.attr_vals !== '') {
      return record.attr_vals.trim().split(' ').map((item: number, index: number) => {
        return <Tag color='blue' key={index} closable onClose={() => tagClose(record, index)}>{item}</Tag>
      })
    } 
  }
  
  // 添加 修改 盒子 显示与 隐藏
  const changeEditBox = (flag: boolean, ...args: string[]) => {
    setIsModalOpen(flag)
    setType(args[0])
  }

  // 点击编辑 显示编辑盒子
  const editBox = (record: {attr_id: number}) => {
    changeEditBox(true, 'edit'),
    setAttrID(record.attr_id + '')
  }

  // 删除动态参数 或者 静态属性
  const deleteParamsAttr = async (record: {attr_id: number}) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除, 是否继续?',
      onOk: async () => {
        const res = await RemoveParamsFnc(catID, record.attr_id)
        if(res.data.meta.status === 200) {
          message.success('删除成功', 1.5, () => {
            getTable(cascaderValue, activeName)
          })
        }
      }
    })
  }

 return (
  <>
    <Button className={style.btn} onClick={() => changeEditBox(true, 'add')}  disabled={btnDisabled} type={btnDisabled === true ? 'default' : 'primary'}>添加{activeName === 'many' ? '参数' : '属性'}</Button>

    <Table dataSource={dataSource} columns={columns} rowKey={(record: {attr_id: number}) => record.attr_id} bordered={true} scroll={{x:500, y: 300}} 
      pagination={{current: pageNow, pageSize: pageSize, total: total, pageSizeOptions: [2,5,10], showQuickJumper: true, showSizeChanger: true, onChange: sizeCurrentChange}}
      expandable={{
        expandedRowRender:(record) => ( <>{subTags(record)} {showBtnTags(record)}</>),
      }}
    />

    {/* 添加参数 属性  修改参数 属性 盒子 */}
    <AddEdit isModalOpen={isModalOpen} changeEditBox={changeEditBox} getTable={getTable} attrID={attrID} cascaderValue={cascaderValue} activeName={activeName} type={type} catID={catID}/>
  </>
 )
}

export default Tables